package com.wangzhen.algorithm.Interview.ThreadPrint2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @description: 创建两个线程，一个线程put 数据，另一个线程检查数据，等检查到5的时候打印并退出
 * @datetime: 2021/4/10   下午5:11
 * @author: 王震
 */
public class ThreadPrint4 {
    volatile static List<Integer> list = new ArrayList<>(10);

    public static void add(int i){
        list.add(i);
    }
    public static int size(){
        return list.size();
    }

    public static void main(String[] args) throws IOException {
        Object lock = new Object();
        Thread thread = new Thread(() -> {
            synchronized (lock){
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("增加i"+i);
                    add(i);
                       if (size()==5){
                            lock.notify();
//                           try {
//                               lock.wait();
//                           } catch (InterruptedException e) {
//                               e.printStackTrace();
//                           }
                       }
                    }

            }
        });

        Thread thread1 = new Thread(() -> {
            try {
                synchronized (lock){
                    lock.wait();
                    System.out.println("容器数量已经达到5，线程二退出");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
        thread.start();
        thread1.start();
        //System.in.read();
    }
}
